package com.smartparking.controller;

import com.smartparking.common.Response;
import com.smartparking.entity.User;
import com.smartparking.repository.UserRepository;
import com.smartparking.security.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final UserRepository userRepository;
    private final JwtUtil jwtUtil;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public AuthController(UserRepository userRepository, JwtUtil jwtUtil) {
        this.userRepository = userRepository;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        if (userRepository.findByUsername(username).isPresent()) {
            return ResponseEntity.badRequest().body(Response.successMessage("用户名已存在"));
        }
        Set<String> set = new HashSet<>();
        set.add("USER");
        User user = User.builder()
                .username(username)
                .password(passwordEncoder.encode(password))
                .roles(set)
                .createdAt(new Date())
                .phone("10086")
                .build();
        userRepository.save(user);
        return ResponseEntity.status(201).body(Response.successMessage("注册成功"));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        Optional<User> opt = userRepository.findByUsername(username);
        if (!opt.isPresent()) {
            return ResponseEntity.status(401).body(Response.errorMessage("认证失败"));
        }
        User user = opt.get();
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return ResponseEntity.status(401).body(Response.errorMessage("认证失败"));
        }
        String token = jwtUtil.generateToken(username);
        return ResponseEntity.ok(Response.success(token));
    }

    @GetMapping("/me")
    public ResponseEntity<?> me(@RequestHeader(value = "Authorization", required = false) String auth) {
        if (auth == null || !auth.startsWith("Bearer ")) {
            return ResponseEntity.status(401).body(Response.errorMessage("未认证"));
        }
        String token = auth.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return ResponseEntity.status(401).body(Response.errorMessage("token无效"));
        }
        String username = jwtUtil.getUsernameFromToken(token);
        Optional<User> opt = userRepository.findByUsername(username);
        if (!opt.isPresent()) return ResponseEntity.status(404).body(Response.errorMessage("用户不存在"));
        return ResponseEntity.ok(opt.get());
    }
}
